package com.example.basecommon.http.rxjava;

import android.support.annotation.NonNull;

import com.example.basecommon.http.LogInterceptor;
import com.example.basecommon.utils.App;
import com.example.basecommon.utils.ConstantUtil;
import com.example.basecommon.utils.LoginUtil;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.readystatesoftware.chuck.ChuckInterceptor;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author dlj
 * des：Retrofit封装工具类
 */
public class HttpUtils {
    private static final String TAG = "HttpUtils";

    public static <T> T request(final Class<T> api) {
        return getRetrofit(api);
    }

    public static <T> T getRetrofit(final Class<T> api) {
        // 初始化Retrofit
        return initRetrofit(initOkHttp()).create(api);
    }

    /**
     * 初始化okhttp
     */
    @NonNull
    private static OkHttpClient initOkHttp() {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
                .readTimeout(ConstantUtil.DEFAULT_TIME, TimeUnit.SECONDS)//设置读取超时时间
                .connectTimeout(ConstantUtil.DEFAULT_TIME, TimeUnit.SECONDS)//设置请求超时时间
                .writeTimeout(ConstantUtil.DEFAULT_TIME, TimeUnit.SECONDS)//设置写入超时时间
                .retryOnConnectionFailure(true);//设置出现错误进行重新连接。
        //添加拦截器
        addInterceptor(builder);
        return builder.build();
    }

    /**
     * 初始化Retrofit
     */
    @NonNull
    private static Retrofit initRetrofit(OkHttpClient client) {
        return new Retrofit.Builder()
                .client(client)
                .baseUrl(ConstantUtil.getServerUrl() + "/")
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    /**
     * 添加各种拦截器
     *
     * @param builder
     */
    private static void addInterceptor(OkHttpClient.Builder builder) {

        //添加chunk显示日志
        ChuckInterceptor chuckInterceptor = new ChuckInterceptor(App.INSTANCE);
        chuckInterceptor.retainDataFor(ChuckInterceptor.Period.ONE_DAY);
        builder.addInterceptor(chuckInterceptor);

        // 添加日志拦截器
        builder.addInterceptor(new LogInterceptor());//添加打印拦截器
        //设cookie
//        Interceptor cookieInterceptor = new Interceptor() {
//            @Override
//            public Response intercept(Chain chain) throws IOException {
//                Request request = chain.request();
//                Response response;
//                Request compressedRequest = request.newBuilder().build();
//                response = chain.proceed(compressedRequest);
//                return response;
//            }
//        };

        //公共参数
        Interceptor paramsInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request oldrequest = chain.request();
                Request newRequest = addParam(oldrequest);
                Response response = chain.proceed(newRequest);
                return response;
            }
        };
        builder.addInterceptor(paramsInterceptor);

    }

    /**
     * 添加公共参数
     *
     * @param oldRequest
     * @return
     */
    private static Request addParam(Request oldRequest) {
        HttpUrl.Builder builder;
        builder = oldRequest.url()
                .newBuilder()
//                .setEncodedQueryParameter("method", method)
//                .setEncodedQueryParameter("v", "v3.0")
        ;

        Request newRequest = oldRequest.newBuilder()
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("Accept", "application/json")
                .addHeader("accessToken", LoginUtil.getToken())
                .method(oldRequest.method(), oldRequest.body())
                .url(builder.build())
                .build();

        return newRequest;
    }
}

